<?php

namespace App\Http\Controllers;

use DB;
use App\Quotation;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Config;


class TopicController extends Controller {

    public $data = array();

    public $goAuth = false;
    public $goReload = false;

    public function __construct(){
        session_start();
        $this->data['user_agent'] = $this->getUserAgent();

        if( empty($_SESSION['user_id']) ){
            $this->goAuth = true;
        }
    }


    //获取所有的话题
    function getAllTopics(){
        if( $this->goAuth ){
            $state          = urlencode("http://".env("APP_URL")."/topics");
            $redirectUrl    = Config::get("lib.oauth_uri")."/auth?client_id=".Config::get("lib.client_id")."&response_type=code&state=$state";
            return redirect($redirectUrl);
        }

        $all_topics = DB::table('topic')->where('is_deleted','=',0)->get();
        $topics_details = DB::select("  select
                                        topic_id , count(*) as topic_detail_count
                                        from
                                        question
                                        where
                                        is_deleted = 0
                                        group by topic_id
                                        ");

        $topic_arr = array();
        $topic_detail_count_arr = array();
        foreach( $topics_details as $key => $val ){
            $topic_detail_count_arr[$val->topic_id] = $val->topic_detail_count;
        }
        foreach( $all_topics as $key => $val ){
            $topic_arr[] = array(
                'id' => $val->id ,
                'count' => isset($topic_detail_count_arr[$val->id]) ? $topic_detail_count_arr[$val->id] : 0 ,
                'name' => $val->name ,
                'cover' => $val->cover
                );
        }

        $this->data['topic_results'] = $topic_arr;

        $this->data['title']        = "拾光问答";
        $this->data['description']  = "所有话题";

        return view('topics' , $this->data);
    }

}
